/*
 * Copyright 2005-2013 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 * 
 * JavaScript - Common
 * Version: 3.0
 */

var shopxx = {
	base: "",
	locale: "zh_CN"
};

var setting = {
	priceScale: "2",
	priceRoundType: "roundHalfUp",
	currencySign: "￥",
	currencyUnit: "元",
	uploadImageExtension: "jpg,jpeg,bmp,gif,png",
	uploadFlashExtension: "swf,flv",
	uploadMediaExtension: "swf,flv,mp3,wav,avi,rm,rmvb,mov",
	uploadFileExtension: "zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx,pdf",
	file_image:"/resources/images/icon_xls.png"
};

// 添加Cookie
function addCookie(name, value, options) {
	if (arguments.length > 1 && name != null) {
		if (options == null) {
			options = {};
		}
		if (value == null) {
			options.expires = -1;
		}
		if (typeof options.expires == "number") {
			var time = options.expires;
			var expires = options.expires = new Date();
			expires.setTime(expires.getTime() + time * 1000);
		}
		document.cookie = encodeURIComponent(String(name)) + "=" + encodeURIComponent(String(value)) + (options.expires ? "; expires=" + options.expires.toUTCString() : "") + (options.path ? "; path=" + options.path : "") + (options.domain ? "; domain=" + options.domain : ""), (options.secure ? "; secure" : "");
	}
}

// 获取Cookie
function getCookie(name) {
	if (name != null) {
		var value = new RegExp("(?:^|; )" + encodeURIComponent(String(name)) + "=([^;]*)").exec(document.cookie);
		return value ? decodeURIComponent(value[1]) : null;
	}
}

// 移除Cookie
function removeCookie(name, options) {
	addCookie(name, null, options);
}

// 货币格式化
function currency(value, showSign, showUnit) {
	if (value != null) {
		var price;
		if (setting.priceRoundType == "roundHalfUp") {
			price = (Math.round(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		} else if (setting.priceRoundType == "roundUp") {
			price = (Math.ceil(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		} else {
			price = (Math.floor(value * Math.pow(10, setting.priceScale)) / Math.pow(10, setting.priceScale)).toFixed(setting.priceScale);
		}
		if (showSign) {
			price = setting.currencySign + price;
		}
		if (showUnit) {
			price += setting.currencyUnit;
		}
		return price;
	}
}

//字符超出打点
function abbreviate(str,maxwidth){
	if(str!=undefined && str.length>maxwidth){ 
		str=(str.substring(0,maxwidth)); 
		str=str+'...';
	 }
	 return str;
}

// 多语言
function message(code) {
	if (code != null) {
		var content = messages[code] != null ? messages[code] : code;
		if (arguments.length == 1) {
			return content;
		} else {
			if ($.isArray(arguments[1])) {
				$.each(arguments[1], function(i, n) {
					content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
				});
				return content;
			} else {
				$.each(Array.prototype.slice.apply(arguments).slice(1), function(i, n) {
					content = content.replace(new RegExp("\\{" + i + "\\}", "g"), n);
				});
				return content;
			}
		}
	}
}

(function($) {

	Array.prototype.contains = function (obj) {  
	    var i = this.length;  
	    while (i--) {  
	        if (this[i] === obj) {  
	            return true;  
	        }  
	    }  
	    return false;  
	}  
	Array.prototype.removeByValue = function(val) {
	  for(var i=0; i<this.length; i++) {
	    if(this[i] == val) {
	      this.splice(i, 1);
	      break;
	    }
	  }
	}

	$.fn.extend({
		lSelect: function(options) {//地区选择
			var settings = {
				choose: "请选择...",
				emptyValue: "",
				cssStyle: {"margin-right": "4px"},
				url: "/member/index/area.jhtml",
				type: "GET",
				locale:"ChinaCN"
			};
			$.extend(settings, options);
			
			var cache = {};
			return this.each(function() {
				var $input = $(this);
				var id = $input.val();
				var treePath = $input.attr("treePath");
				var id_name = $input.attr("id");
				var selectName = $input.attr("name") + "_select";
				if(id_name!=undefined && id_name!=''){//修复带[]的名称bug
					selectName = id_name + "_select";
				}else{
					selectName = $input.attr("name") + "_select";
				}
				
				if (treePath != null && treePath != "") {
					var ids = (treePath + id + ",").split(",");
					var $position = $input;
					for (var i = 1; i < ids.length; i ++) {
						$position = addSelect($position, ids[i - 1], ids[i]);
					}
				} else {
					addSelect($input, null, null);
				}
				
				function addSelect($position, parentId, currentId) {
					$position.nextAll("select[name=" + selectName + "]").remove();
					if ($position.is("select") && (parentId == null || parentId == "")) {
						return false;
					}
					if (cache[parentId] == null) {
						var param = {locale:settings.locale};
						if(parentId != null){
							param.parentId = parentId;
						}
						$.ajax({
							url: settings.url,
							type: settings.type,
							data: param,
							dataType: "json",
							cache: false,
							async: false,
							success: function(data) {
								cache[parentId] = data;
							}
						});
					}
					var data = cache[parentId];
					if ($.isEmptyObject(data)) {
						return false;
					}
					var select = '<select class="areaId_select" name="' + selectName + '">';
					if (settings.emptyValue != null && settings.choose != null) {
						select += '<option value="' + settings.emptyValue + '">' + settings.choose + '</option>';
					}
					$.each(data, function(value, name) {
						if(value == currentId) {
							select += '<option value="' + value + '" selected="selected">' + name + '</option>';
						} else {
							select += '<option value="' + value + '">' + name + '</option>';
						}
					});
					select += '</select>';
					return $(select).css(settings.cssStyle).insertAfter($position).bind("change", function() {
						var $this = $(this);
						if ($this.val() == "") {
							var $prev = $this.prev("select[name=" + selectName + "]");
							if ($prev.size() > 0) {
								$input.val($prev.val());
							} else {
								$input.val(settings.emptyValue);
							}
						} else {
							$input.val($this.val());
						}
						addSelect($this, $this.val(), null);
					});
				}
			});
			
		}

	});

})(jQuery);

/**图片绑定一个默认图*/
document.addEventListener("error", function (e) {
    var elem = e.target;
    if (elem.tagName.toLowerCase() === 'img') {
        elem.src = '/resources/images/default-img.jpg';
    }
}, true);

// 令牌
$().ready(function() {
	
	setTimeout(function(){
		$(".pup-loading").remove();
	},200);
	
	if ($.tools != null) {
		var $tab = $("#tab");
		var $title = $("#inputForm :input[title], #inputForm label[title]");

		// Tab效果
		$tab.tabs("table.tabContent, div.tabContent", {
			tabs: "input"
		});
	
		// 表单提示
		$title.tooltip({
			position: "center right",
			offset: [0, 4],
			effect: "fade"
		});
	}

	// 验证消息
	if($.validator != null) {
		$.validator.setDefaults({
			errorClass: "fieldError",
			ignore: ".ignore",
			ignoreTitle: true,
			errorPlacement: function(error, element) {
				var fieldSet = element.closest("span.fieldSet");
				if (fieldSet.size() > 0) {
					error.appendTo(fieldSet);
				} else {
					error.insertAfter(element);
				}
			},
			submitHandler: function(form) {
				return false;
			}
		});
	}
	
	
	/**给输入框绑定一个清除的按钮*/
	$.fn.addClearBtn = function(callback){    
	   $(this).each(function(){
	   		var $this = $(this);
	   		var $f_sapn = $('<span class="ax-span"></span>');
			var $a = $('<a class="close" data-event="callClose" name="e" href="javascript:void(0);" style=" display: none;">'+
			'</a>');
			 $a.click(function(){
			 	if(callback!=undefined && typeof callback == "function"){
			 		callback();
			 	}else{
			 		$this.val("").focus();
			 	}
			 });
		   $this.after($f_sapn);
		   $f_sapn.append($this).append($a);
		
		   $f_sapn.click(function(){
		   		$this.focus();
		   }).mouseover(function(){
		   		if(!$this.prop("disabled") && !$this.prop("readonly")){
		   			$a.css("display", "inline-block");
		   		}
		   }).mouseout(function(){
		   		$a.css("display", "none");
		   })
	   });
		
	};  
		
	$("input:text[btn-fun='clear']").addClearBtn();

});

// 编辑器
if(typeof(KindEditor) != "undefined") {
	KindEditor.ready(function(K) {
		var option = {
			height: "350px",
			items: [
				"source", "|", "undo", "redo", "|", "preview", "print", "template", "cut", "copy", "paste",
				"plainpaste", "wordpaste", "|", "justifyleft", "justifycenter", "justifyright",
				"justifyfull", "insertorderedlist", "insertunorderedlist", "indent", "outdent", "subscript",
				"superscript", "clearhtml", "quickformat", "selectall", "|", "fullscreen", "/",
				"formatblock", "fontname", "fontsize", "|", "forecolor", "hilitecolor", "bold",
				"italic", "underline", "strikethrough", "lineheight", "removeformat", "|", "file_source",
				"flash", "media", "insertfile", "table", "hr", "emoticons", "baidumap", "pagebreak",
				"anchor", "link", "unlink"
			],
			langType: shopxx.locale,
			syncType: "form",
			filterMode: false,
			pagebreakHtml: '<hr class="pageBreak" \/>',
			allowFileManager: true,
			filePostName: "file",
			fileManagerJson: "",
			uploadJson: "",
			uploadImageExtension: setting.uploadImageExtension,
			uploadFlashExtension: setting.uploadFlashExtension,
			uploadMediaExtension: setting.uploadMediaExtension,
			uploadFileExtension: setting.uploadFileExtension,
			extraFileUploadParams: {
				token: getCookie("token")
			},
			afterChange: function() {
				this.sync();
			}
		};
		
		editor = K.create("#editor", option);

	});
}

function clearSelect(e){
	var $this = $(e);
	var value = $this.val();
	if(value==undefined || value.length==0){
		var $tr = $(e).closest("div.search");
		$this.prev("input").val("");
	}
}

/**初始化下拉的多选框*/
function initMultipleSelect(){
	$("input.doStatus").on("click",function(){
		var $next = $(this).next();
		if($next.attr("data-value") == "off"){
			$next.attr("data-value","on");
			$next.show();
		}
		else{
			$next.attr("data-value","off");
			$next.hide();
		}
		
	});
	$(".checkbox-style").hover(function(){
		if($(this).find(".doStatus") != undefined && $(this).find(".doStatus").val() != ""){
			$(this).find("a.deleteText").css("display","block");
		}
		},
		function(){
			$(this).find("a.deleteText").css("display","none");
		}
	)
	$(document).on('click',function(e){
		$(".statusList:visible").each(function(){
			var $this = $(this);
			var s1 = $this.closest('.checkbox-style');
			if(!s1.is(e.target) && s1.has(e.target).length===0){
				s1.find(".doStatus").css("box-shadow","0 0 0 transparent");
				$this.attr("data-value","off").hide();
			}
		});
	})
	$("input.js-iname").on("click",function(e){
		var $statusList =$(e.target).closest(".statusList");
		var $checkeds = $statusList.find("input[type='checkbox']:checked");
		var text='';
		for(var i=0;i<$checkeds.length;i++){
			var c=$checkeds.eq(i).parent().text();
			text += c.concat(";");
		}
		$statusList.prev().attr("title",text).val(text);
		if($checkeds.length>0){
			$(this).closest(".checkbox-style").find("a.deleteText").css("display","block");
		}else{
			$(this).closest(".checkbox-style").find("a.deleteText").css("display","none");
		}
		
	});

	clearText = function(e){
		$(e).next().val("");
		$(e).closest(".checkbox-style").find("input[type='checkbox']").attr("checked",false);
	}
}

/**刷新并滚动到锚点位置*/
function reflush_wf(){
	window.parent.scoll_flag=1;
	location.reload(true);
}

function getfileObj(fileName,name,suffix){
	var obj = new Object();
	obj.fileName = fileName;
	var index = fileName.lastIndexOf('.');
	if(index>=0){
		obj.name = (name==null || name==undefined)?fileName.substring(0,index):name;
		obj.suffix = (suffix==null || suffix==undefined)?fileName.substring(index+1,fileName.length):suffix;
	}else{
		obj.name = fileName;
		obj.suffix = '';
	}
	
	return obj;
}

function createFileStr(options){
	var option = {
		url:'',
		fileName:'',
		name:'',
		suffix:'',
		time:'',
		textName:'',
		hideValues:{}
	};
	
	$.extend(option, options);
	
	var hide_str = '';
	var hideValues = option.hideValues;
	for(var key in hideValues){
		hide_str+='<input type="hidden" name="'+key+'" value="'+hideValues[key]+'">'
	}
	
	if(option.time.length==0){
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth()+1;
		var day = date.getDate();
		option.time = year+'-'+month+'-'+day;
	}else if(option.time.length > 10){
		option.time = option.time.substring(0,10);
	}
	
	var html = '<div class="upload-list"><div class="ul-box">'+
							'<div class="pic"><a href="'+option.url+'" target="_blank"><img src="/resources/images/icon_xls.png"></a></div>'+
							'<div  class="txt-box">'+
							'<b><textarea class="text t-edit"  name="'+option.textName+'">'+option.name+'</textarea>&nbsp;.&nbsp;'+option.suffix+'</b>'+
							'<p>'+option.time+'</p>'+
							'</div>'+
							 hide_str+
							'</div>';
	return html;
}

/**
*	限定只能输入数字,值变化时调用（obj：按钮对象，decimalPlaces：精确的小数位，allowNegative：是否允许负数）
*	例： oninput="extractNumber(this, 2, false)" onpropertychange="extractNumber(this, 2, false)"
*/
function extractNumber(obj, decimalPlaces, allowNegative,event) {

	if(event!=undefined){
		if((typeof obj.oninput == "function" )&& (typeof obj.onpropertychange == "function") && event.type=="propertychange"){
			return false;
		}
		
		if(event.type=="input" || event.type=="propertychange"){
			var _xval = obj._xval;
			if(_xval != obj.value  || (_xval==undefined || (_xval!=undefined && _xval.toString().length != obj.value.toString().length))) {
				obj._xval = obj.value;
			}else{
				return false;
			}
		}
	}
	
    var temp = obj.value;
    var minData = obj.getAttribute('minData');
    var maxData = obj.getAttribute('maxData');


    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) {
    	if(minData!=undefined){
    		minData = Number(minData);
    		temp = Number(temp);
    		if(temp<minData){
    			obj.value = minData;
				obj._xval = minData;
    		}
    	} 
		if(maxData!=undefined){
    		maxData = Number(maxData);
    		temp = Number(temp);
    		if(temp>maxData){
    			obj.value = maxData;
				obj._xval = maxData;
    		}
    	}
    	return true
    }


    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');


    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }


    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            // and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;
        }
    }
    
    if(minData!=undefined){
   		minData = Number(minData);
   		if(Number(temp)<minData){
   			temp = minData;
   		}
   	}
	if(maxData!=undefined){
   		maxData = Number(maxData);
   		if(Number(temp)>maxData){
			temp = maxData;
   		}
   	}

    obj.value = temp;
	obj._xval = temp;
	return true;
}

function decrease(e,event){
	if(event.button==0){
		var ns=e.nextElementSibling;   //获得s的下一个兄弟节点
		if(ns.disabled)return false;
		var val = Number(ns.value);
		if(!isNaN(val)){
			val = accSub(val,1);
			var minData = ns.getAttribute('minData');
			if(minData!=null && val<minData){
				val = minData;
			}
			if(ns.value!=val){
				ns.disabled = true;
				ns.value = val;
				ns.disabled = false;
			}
		}
	}
}

function increase(e,event){
	if(event.button==0){
		var ps=e.previousElementSibling;  //得到s的上一个兄弟节点
		if(ps.nodeName!='INPUT')ps = ps.previousElementSibling;
		if(ps.disabled)return false;
		var val = Number(ps.value);
		if(!isNaN(val)){
			val = accAdd(val,1);
			var maxData = ps.getAttribute('maxData');
			if(maxData!=null && val>maxData){
				val = maxData;
			}
			if(ps.value!=val){
				ps.disabled = true;
				ps.value = val;
				ps.disabled = false;
				
			}
		}
	}
}

function accDiv(arg1,arg2){  
	var t1=0,t2=0,r1,r2;  
	try{t1=arg1.toString().split(".")[1].length}catch(e){}  
	try{t2=arg2.toString().split(".")[1].length}catch(e){}  
	with(Math){  
		r1=Number(arg1.toString().replace(".",""))  
		r2=Number(arg2.toString().replace(".","")) 
		return accMul((r1/r2),pow(10,t2-t1));  
	}  
} 
 //乘法 
function accMul(arg1,arg2){  
	var m=0,s1=arg1.toString(),s2=arg2.toString();  
	try{m+=s1.split(".")[1].length}catch(e){}  
	try{m+=s2.split(".")[1].length}catch(e){}  
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)  
}  
//加法  
function accAdd(arg1,arg2){  
	var r1,r2,m;  
	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  
	m=Math.pow(10,Math.max(r1,r2))  
	return (arg1*m+arg2*m)/m  
}  
//减法  
function accSub(arg1,arg2){ 
	var r1,r2,m,n; 
	try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
	try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
	m=Math.pow(10,Math.max(r1,r2)); 
	n=(r1>=r2)?r1:r2; 
	return ((arg1*m-arg2*m)/m).toFixed(n); 
}


/**
$("label.checkhid").live("click", function () {
	var id = $(this).attr("data-id");
	if($(this).find("input").attr("type")=="checkbox"){
    	if ($(this).find("input[type=checkbox]:checked").val() == undefined) {
       		$(this).find(".check_box").removeClass("checked").find(":checkbox").attr("checked", false);
    	} else {
        	$(this).find(".check_box").addClass("checked").find(":checkbox").attr("checked", true);
    	}
    }else{
    	if ($(this).find("input[type=radio]:checked").val() == undefined) {
         $(this).find(".check_box").removeClass("checked").find(":radio").removeAttr("checked"); 
     	} else {
         $($("#"+id)).find(".check_box").removeClass("checked").find(":radio").attr("checked", false);
         $(this).find(".check_box").addClass("checked").find(":radio").attr("checked", true);
   		}
	}
});*/
